package middleware


import (
	"strings"
	"gin/chibuda/app/utils"
	"github.com/gin-gonic/gin"
	goSign "github.com/parkingwang/go-sign"
)

func CheckSign() gin.HandlerFunc {
	return func(c *gin.Context) {
		sign := c.Request.Header.Get("__SIGN__")
		if sign == "" {
			c.JSON(utils.SignErrCode, gin.H{"msg":"签名不能为空",})
			c.Abort()
			return
		}
		Parms := utils.Input(c)
		if Parms["time_stamp"] == "" || Parms["nonce_str"] == ""{
			c.JSON(utils.SignErrCode, gin.H{"msg":"签名参数缺失",})
			c.Abort()
			return
		}
		if len(Parms["time_stamp"]) !=10 || utils.Time() - utils.Int64(Parms["time_stamp"]) > 300 {
			c.JSON(utils.SignErrCode, gin.H{"msg":"时间戳格式有误，或超时",})
			c.Abort()
			return
		}
		signer := goSign.NewGoSignerMd5()
		for key,val := range Parms {
			signer.AddBody(strings.ToUpper(key),val)
		}
		//秘钥
		signer.SetSignBodySuffix("d93047a4d6fe6111")
		serverSign := signer.GetSignature()
		if serverSign!=sign{
			c.JSON(utils.SignErrCode, gin.H{"msg":"签名错误",})
			c.Abort()
			return
		}
		c.Set("parms",Parms)
	}
}